# -*- coding: utf-8 -*-
# @Time:2021/08/04 21:28
# @Author:Cindy
import json

from flask import request
from flask_restful import Resource

from models.task import Task
from models.testcases import TestCase
from server import app, db
from utils.execute_tools import ExecuteTools


class TaskService(Resource):

    def get(self):
        """
        获取测试任务列表
        :return:
        """
        tasks = Task.query.all()
        tasks_data = [task.as_dict() for task in tasks]
        app.logger.info(f"获取到的任务列表为{tasks_data}")

        return {'error': 0, 'msg': tasks_data}

    def post(self):
        """
        1.调用Jenkins执行测试用例
        2.执行用例后，将执行记录写入数据库
        :return:
        """
        data = request.json
        # nodeids = data['nodeid']
        nodeids = [i["nodeid"] for i in data]
        # ['test_setup_teardow.py', 'test_order.py']
        # 转换为"test_setup_teardow.py test_order.py"
        # 方便 pytest执行 test_setup_teardow.py test_order.py
        nodeids = " ".join(nodeids)
        app.logger.info(f"测试用例为：{nodeids}")
        # 调用Jenkins执行测试用例
        report = ExecuteTools.invoke(nodeids)
        app.logger.info(f'执行测试用例返回结果为：{report}')
        # 将执行记录写入数据库
        task = Task(remark=nodeids, report=report)
        db.session.add(task)
        db.session.commit()
        db.session.close()

        return {'error': 0, 'msg': 'ok'}
